package models

import (
	"gitee.com/sansaniot/ssiot-core/httpmvc/model"

	cDto "ssadmin/common/query"
	"ssadmin/internal/admin/models/query"
)

type SysLog struct {
	Id          string         `json:"id" gorm:"primaryKey"`
	Uri         string         `json:"uri"`
	Ip          string         `json:"ip"`
	Region      string         `json:"region"`
	Username    string         `json:"username"`
	Method      string         `json:"method"`
	Param       string         `json:"param"`
	Response    string         `json:"response"`
	Latency     string         `json:"latency"`
	Code        int            `json:"code"`
	OperateTime cDto.LocalTime `json:"operateTime"`
	AgencyId    string         `json:"agencyId"`

	model.Model
}

func (SysLog) TableName() string {
	return "sys_operate_log"
}

func (e *SysLog) Generate() interface{} {
	o := *e
	return &o
}

func (e *SysLog) GetId() interface{} {
	return e.Id
}

func (e *SysLog) GetLatestAddressByUser(username string) error {
	// 用first会自动加上id排序，因此用take
	return e.Orm.Where(SysLog{Username: username}).Order("operate_time DESC").Take(e).Error
}

func (e *SysLog) FindLogList(req *query.SysLogQuery) (err error, result interface{}) {
	list := make([]SysLog, 0)
	var count int64
	if req.PageIndex > 0 && req.PageSize > 0 {
		err = e.FindPage(&list, &count,
			cDto.MakeCondition(req.GetNeedSearch()),
			cDto.OrderDest("operate_time", true, req.OrderBy),
			cDto.Paginate(req.GetPageSize(), req.GetPageIndex()),
		)
		result = &cDto.Page{
			Records:   list,
			Total:     count,
			PageSize:  req.GetPageSize(),
			PageIndex: req.GetPageIndex(),
			Pages:     (count + int64(req.GetPageSize()) - 1) / int64(req.GetPageSize()),
			Other:     nil,
		}
	} else {
		err = e.FindList(&list,
			cDto.MakeCondition(req.GetNeedSearch()),
			cDto.OrderDest("operate_time", true, req.OrderBy),
		)
		result = list
	}
	return
}
